import { observable, action } from 'mobx';
import * as Api from '../../apis/filePreview';

const initalState = {
  fileRight: false,
  fileLoading: true,
  fileName: '',
  fileIsImg: false,
  fileId: '',
  fileMsg: '',
  previewUrl: '',
  contentLoading: false,
  filePath: '',
  contentMsg: '',
  fileDownload: '',
};
export default class FilePreviewStore {
  @observable fileLoading = initalState.fileLoading; // 加载
  @observable fileRight = initalState.fileRight; // 权限
  @observable fileName = initalState.fileName; // 文件名称
  @observable fileIsImg = initalState.fileIsImg; // 文件是否是图片类型
  @observable fileId = initalState.fileId;
  @observable fileMsg = initalState.fileMsg; // 文件获取失败提示信息
  @observable previewUrl = initalState.previewUrl; // 图片预览地址
  @observable contentLoading = initalState.contentLoading; // 内容加载
  @observable filePath = initalState.filePath; // 内容预览地址
  @observable contentMsg = initalState.contentMsg; // 内容出错消息
  @observable fileDownload = initalState.fileDownload; // 文件下载地址

  @action setStoreState = (params) => {
    Object.keys(params).forEach((key) => {
      this[key] = params[key];
    });
  }

  @action clear = () => this.setStoreState(initalState);

  // 获取附件预览基本信息
  @action getFileInfo = (params) => {
    this.fileLoading = true;
    Api.getFilePreviewInfoForPC(params).then(action((res) => {
      this.fileRight = res.hasRight || false;
      this.fileName = res.fileName || '';
      this.fileMsg = res.message || '';
      this.fileIsImg = res.isImg;
      this.previewUrl = res.previewUrl;
      this.fileLoading = false;
      this.fileId = res.mailFileId;
      this.fileDownload = res.filelink;
      if (res.hasRight && !res.isImg && !res.message) {
        this.getFileContent({ fileid: this.fileId });
      }
    }));
  }

  @action getFileContent = (params) => {
    this.contentLoading = true;
    Api.convertForEmail(params).then(action((res) => {
      // 存在res.data，就是去拿path, 其他的值，就取message
      this.filePath = res.data[0].path || '';
      this.contentMsg = res.message || '';
      this.contentLoading = false;
    }));
  }
}
